package com.guo.rpc.client;

import com.guo.rpc.client.handler.ServiceRemoteInvokeResponseHandler;
import com.guo.rpc.codec.Packet;
import com.guo.rpc.codec.ServiceRemoteInvokeRequest;
import com.guo.rpc.codec.ServiceRemoteResponse;
import com.guo.rpc.handler.PacketCodecHandler;
import com.guo.rpc.handler.Spliter;
import com.guo.rpc.server.handler.ServiceRemoteInvokeHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Arrays;
import java.util.concurrent.Callable;

/**
 * @Author: ljguo4
 * @email: ljguo4@iflytek.com
 * @Date: 2021/7/15 19:20
 * @Description:
 * @version: 1.0
 */
public class RpcClientStub {
    public static void main(String[] args) {
        RpcClientStub rpcClientStub = new RpcClientStub();
//        rpcClientStub.initRpcClient();
    }

    private Channel channel;

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    public void initRpcClient(Packet packet) {
        EventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(worker)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new Spliter())
                                .addLast(PacketCodecHandler.INSTANCE)
                                .addLast(ServiceRemoteInvokeResponseHandler.INSTANCE);
                    }
                });
        bootstrap.connect("localhost", 8088)
                .addListener(future -> {
            if (future.isSuccess()) {
                Channel channel = ((ChannelFuture) future).channel();
                this.channel = channel;
//                ServiceRemoteInvokeRequest req = new ServiceRemoteInvokeRequest();
//                req.setVersion("1.0");
//                req.setMethodName("getHelloStr");
//                req.setServiceName("HelloServiceImpl");
//                req.setArgs(new String[]{"test"});
                channel.writeAndFlush(packet);

            } else {
                System.out.println("连接失败");
            }
        });
    }
}
